/*
 * Copyright (C) 2009-2010 Valerio Fuoglio <valerio.fuoglio@gmail.com>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

using System.Collections.Generic;
using System.Net;
using Lastfm.Scrobbling;
using Lastfm.Services;

namespace LightScrobbler
{
    internal class ScrobbleSessionData
    {
        private static ScrobbleSessionData _uniqueInstance;

        private Session _session;
        private SessionState _sessionState;

        // Must store a not authenticated session, because covers cannot be 
        // fetched from an authenticated one. Is it a bug?
        private Session _unauthSession;

        private ScrobbleSessionData()
        {
            RejectedTracks = new Dictionary<Entry, string>();
            PlayedTracks = new List<Entry>();
            SkippedTracks = new List<Entry>();
            Options = new Dictionary<LightScrobblerOptions, object>();
            _session = null;
        }

        public string Username { get; set; }

        public string Password { get; set; }

        public string FilePath { get; set; }

        public List<Entry> PlayedTracks { get; set; }

        public List<Entry> SkippedTracks { get; set; }

        public List<Entry> SelectedTracks { get; set; }

        public bool SuccessifullySent { get; set; }

        public bool DriveLocked { get; set; }

        public Dictionary<Entry, string> RejectedTracks { get; set; }

        public Dictionary<LightScrobblerOptions, object> Options { get; set; }

        public Session NotAuthenticatedSession
        {
            get
            {
                for (int attempt = 0; attempt <= 2; attempt++)
                {
                    try
                    {
                        if (_unauthSession == null)
                            _unauthSession = new Session(Utils.ApiKey, Utils.ApiSecret);
                    }
                    catch (ServiceException e)
                    {
                        switch (e.Type)
                        {
                            default:
                                continue;
                        }
                    }
                    catch (WebException)
                    {
                        _unauthSession = null;
                        attempt = 3; // Force exit
                    }
                }
                return _unauthSession;
            }
        }

        public Session Session
        {
            get
            {
                if (Username == null || Password == null) return null;

                for (int attempt = 0; attempt <= 2; attempt++)
                {
                    try
                    {
                        if (_session == null)
                            _session = new Session(Utils.ApiKey, Utils.ApiSecret);
                        if (_session.Authenticated) break;
                        _session.Authenticate(
                            Username,
                            Password);
                        _sessionState = SessionState.Authendicated;
                    }
                    catch (ServiceException e)
                    {
                        switch (e.Type)
                        {
                            case ServiceExceptionType.AuthenticationFailed:
                                _sessionState = SessionState.AuthenticationFailed;
                                attempt = 3; // Force exit
                                break;
                            case ServiceExceptionType.ExpiredToken:
                            case ServiceExceptionType.TokenError:
                                _sessionState = SessionState.Outdated;
                                _session = null;
                                continue;
                            default:
                                _sessionState = SessionState.Unavailable;
                                break;
                        }
                    }
                    catch (WebException)
                    {
                        _sessionState = SessionState.NoNetwork;
                        attempt = 3; // Force exit
                    }
                }
                return _session;
            }
        }

        public SessionState SessionState
        {
            get { return _sessionState; }
        }

        public void InvalidateSession()
        {
            // Force to ask a new session
            _session = null;
        }

        public static ScrobbleSessionData GetInstance()
        {
            if (_uniqueInstance == null)
            {
                _uniqueInstance = new ScrobbleSessionData();
            }
            return _uniqueInstance;
        }

        public static void Reset()
        {
            _uniqueInstance = null;
        }

        internal void InvalidateNotAuthenticatedSession()
        {
            // Force to ask a new session
            _unauthSession = null;
        }
    }
}